package java.hilyb.record;

import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.*;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.*;
import android.widget.*;
import java.hilyb.dbtest.DBHelper;
import java.hilyb.dbtest.R;
import java.hilyb.dbtest.domain.Category;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * User: wlai
 * Date: 12/26/2014
 * Time: 15:43 PM
 */
public class CategoryMgr extends Activity {
    private ListView categoryList;
    private Handler handler = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.category_mgr);
        TextView tv = (TextView) findViewById(R.id.label1);
        TextView label2 = (TextView) findViewById(R.id.label2);
        String html = "<img src=\"image1\" />Image1<br/><img src=\"image2\" />Image2";
        CharSequence str = Html.fromHtml(html, new Html.ImageGetter() {
            @Override
            public Drawable getDrawable(String s) {
                Drawable d = null;
                if ("image1".equals(s)) d = getResources().getDrawable(R.drawable.p1);
                if ("image2".equals(s)) d = getResources().getDrawable(R.drawable.p2);
                if (d != null) d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                return d;
            }
        }, null);

        tv.setText(str);

        CharSequence text2 = "Click Here";
        SpannableString ss = new SpannableString(text2);
        ClickableSpan span = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                Toast.makeText(CategoryMgr.this, "clicked", Toast.LENGTH_LONG).show();
            }
        };
        ss.setSpan(span, 6, text2.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        label2.setText(ss);
        label2.setTextSize(20);
        label2.setMovementMethod(LinkMovementMethod.getInstance());


        categoryList = (ListView) findViewById(R.id.categoryList);
        DBHelper helper = new DBHelper(this);
        List<Category> categories = helper.getTopCategories();
        categoryList.setAdapter(new CategoryItemAdapter(this, categories));
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                TextView textView3 = (TextView) findViewById(R.id.label3);
                textView3.setText(msg.getData().getString("html"));
            }
        };

        EditText editText1 = (EditText) findViewById(R.id.editText1);
        editText1.append(str);
//        HandlerThread handlerThread=new HandlerThread("thread1");
//        handlerThread.start();

      /*  handler.post(new Runnable() {
            @Override
            public void run() {
                doTest();
            }
        });*/
       /* new Thread() {
            @Override
            public void run() {
                doTest();
            }
        }.start();*/
    }

    private void doTest() {

        try {
            HttpURLConnection conn = (HttpURLConnection) (new URL("http://www.baidu.com").openConnection());
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder(1024);
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
            conn.disconnect();
            Message message = new Message();
            Bundle bundle = new Bundle();
            bundle.putString("html", sb.toString());
            message.setData(bundle);
            handler.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.category, menu);
        return true;
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
            if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
                try {
                    Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e) {
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.newCategory: {
                Intent intent = new Intent(this, CategoryDetail.class);
                startActivity(intent);
                break;
            }
            case android.R.id.home:
                Toast.makeText(this, "You clicked on the Application icon", Toast.LENGTH_LONG).show();
                return true;
        }
        return true;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
       /* FragmentManager mgr = getFragmentManager();
        FragmentTransaction tx = mgr.beginTransaction();
        Fragment f1 = mgr.findFragmentById(R.id.id_f1);
        if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE) {
            tx.hide(f1);
        }else{
            tx.show(f1);
        }
        tx.commit();*/
    }
}

class CategoryItemAdapter extends BaseAdapter {
    private LayoutInflater inflater;
    private List<Category> categories;

    public CategoryItemAdapter(Context ctx, List<Category> data) {
        inflater = LayoutInflater.from(ctx);
        this.categories = data;
    }

    @Override
    public int getCount() {
        return categories.size();
    }

    @Override
    public Object getItem(int i) {
        return categories.get(i);
    }

    @Override
    public long getItemId(int i) {
        return categories.get(i).getId();
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if (view == null) {
            view = inflater.inflate(R.layout.category_item, null);
            TextView label = (TextView) view.findViewById(R.id.label1);
            ImageView imgView = (ImageView) view.findViewById(R.id.imgView);
            CategoryItemHolder holder = new CategoryItemHolder();
            holder.imageView = imgView;
            holder.textView = label;
            view.setTag(holder);

        }
        Category category = (Category) getItem(i);
        CategoryItemHolder holder = (CategoryItemHolder) view.getTag();
        holder.imageView.setImageResource(R.drawable.p1);
        holder.textView.setText(category.getName());
        return view;
    }
}

class CategoryItemHolder {
    public TextView textView;
    public ImageView imageView;
}